using System;
using System.Collections.Generic;
using System.Linq;

namespace EternitySolver.Core
{
    public class TileBag
    {
        private readonly List<Tile> _ordered;
        private List<Tile> _jumbled;

        public List<Tile> Ordered { get { return _ordered; } }
        public List<Tile> Jumbled { get { return _jumbled; } }

        public TileBag()
        {
            _ordered = new List<Tile>();
            _jumbled = new List<Tile>();
        }

        public void Add(Tile tile)
        {
            _ordered.Add(tile);
            _jumbled.Add(tile);
        }

        public void Jumble()
        {
            _jumbled = _jumbled.OrderBy(o => Guid.NewGuid().ToString()).ToList();
        }

        public void Remove(Tile tile)
        {
            _ordered.Remove(tile);
            _jumbled.Remove(tile);
        }

        public List<TileOrientation> FindTileLayoutsThatFit(TileSpecification specification)
        {
            var temp = new List<TileOrientation>();
            foreach (TileOrientation fit in _jumbled.SelectMany(tile => tile.Fits(specification)))
            {
                bool exists = false;
                foreach (TileOrientation layout in temp)
                {
                    if (layout.Matches(fit))
                    {
                        exists = true;
                        break;
                    }
                }
                if (!exists) temp.Add(fit);
            }
            return temp;
        }
    }
}